﻿using Microsoft.AspNetCore.Mvc;

namespace DataModels.Dto
{
    public class ResponseModel: IActionResult
    {
        /// <summary>
        /// 请求响应实体类
        /// </summary>
        public ResponseModel()
        {
            Code = 200;
            Message = "操作成功";
        }
        /// <summary>
        /// 响应代码
        /// </summary>
        public int Code { get; set; }
        /// <summary>
        /// 响应消息内容
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 返回的响应数据
        /// </summary>
        public object? Data { get; set; }

        public ResponseModel Success(object data)
        {
            Code = 200;
            Data = data;
            return this;
        }
        public ResponseModel Error(string message,int? code = 500)
        {
            Code = (int)(code.HasValue? code : 500);
            Message = message;
            return this;
        }
        /// <summary>
        /// 设置响应状态为错误
        /// </summary>
        /// <param name="message"></param>
        public void SetError(string message = "错误")
        {
            Code = 500;
            Message = message;
        }

        /// <summary>
        /// 设置响应数据
        /// </summary>
        /// <param name="data"></param>
        public void SetData(object data)
        {
            Data = data;
        }

        public async Task ExecuteResultAsync(ActionContext context)
        {
            // 创建一个ObjectResult并设置状态码和响应内容
            var objectResult = new ObjectResult(this)
            {
                StatusCode = Code
            };

            // 委托给ASP.NET Core框架处理实际的响应生成
            await objectResult.ExecuteResultAsync(context);
        }
    }
}
